<?php
namespace app\index\controller;
use think\Controller ;
//use think\Request;
use Db;
//use EasyWeChat\Factory;

class Index extends Controller
{
    public function index()
    {

        if (strpos($_SERVER['HTTP_USER_AGENT'],'Mobile'))
        {
           $type=1;
        }else{
            $type=2;
        }

        $this->assign('phone',13202398471);
//        dump($type);

        $this->assign('type',$type);
        return $this->fetch();
    }

    //申请贷款
    public function apply(){

        $user_name = input('user_name');
        $phone = input('phone');

        if(trim($user_name)==''){
            return ['code'=>100,'msg'=>'请输入正确的姓名'];
        }

        if(!preg_match("/^1[3456789]\d{9}$/",$phone)){
            return ['code'=>100,'msg'=>'请输入正确的手机号码'];
        }

        $time = strtotime('today');
        $ip = ip2long(request()->ip());
        $count = Db::name('user')->where('create_time','>=',$time)->where('ip',$ip)->count();

        if($count>=10){
            return ['code'=>100,'msg'=>'今日申请已达上限'];
        }

        $row = Db::name('user')->where('phone',$phone)->find();
        if($row){
            return ['code'=>100,'msg'=>'当前手机号已申请'];
        }

        $insertData = array(
            'user_name'=>$user_name,
            'phone' => $phone,
            'ip' => $ip,
            'create_time'=>time()
        );


        $add = Db::name('user')->insert($insertData);

        if($add){
            return ['code'=>200,'msg'=>'申请成功'];

        }else{
            return ['code'=>100,'msg'=>'申请失败'];

        }
    }

    //获取验证码
    public function phoneCode(){

        if(request()->isAjax()){
            $phone  = input('phone');

            if(!check_phone($phone)){
                $this->error('请输入正确的手机号码');
            }


            $code = create_code();

            //发送短信
            $res = send_sms($phone,1,['code'=>$code]);

            if($res['Code']=='OK'){
                if(cache('login_'.$phone,$code,300)){
                    $this->success('发送成功');
                }else{
                    $this->error('系统繁忙，请稍后再试');
                }

            }else{
                $this->error('发送失败,请稍后再试');
            }
        }

    }


    public function ajaxError(){

        if(request()->isAjax()){

            exit(json_encode(['code'=>0,'msg'=>'请刷新页面登录']));
        }
    }
}
